﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSoict.Models;
using Newtonsoft.Json;

namespace MVCSoict.Controllers
{
    public class DepartmentController : Controller
    {
        private staffsoictEntities1 db = new staffsoictEntities1();
        private JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        };
        // GET: /Department/
        public ActionResult Index()
        {
            return View(db.Departments.ToList());
        }

        public string Select(string keyword, int page, int pagesize)
        {
            string jsonResult = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "department_select"))
                {
                    using (var context = new staffsoictEntities1())
                    {
                        var depart = from d in context.Departments
                                     where d.name.Contains(keyword)
                                     orderby d.did
                                     select d;

                        var pageData = depart.Skip((page - 1) * pagesize).Take(pagesize).ToList();
                        foreach (var de in pageData)
                        {
                            jsonResult += JsonConvert.SerializeObject(de, jsonSettings);
                        }
                    }
                }
            }
            return jsonResult;
        }

        public string Add([Bind(Include = "did,name")] Department department)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "department_add"))
                {
                    try
                    {
                        db.Departments.Add(department);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(department, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        //tested
        public string Update([Bind(Include = "did,name")] Department department)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "department_update"))
                {
                    try
                    {
                        db.Entry(department).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(department, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Get(string id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "department_get"))
                {
                    try
                    {
                        var deprs = from d in db.Departments
                                    where d.did.Equals(id)
                                    select d;
                        if ((deprs.ToList<Department>().Count() > 0))
                            res = JsonConvert.SerializeObject(deprs.ToList<Department>()[0], jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        // GET: /Department/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Department department = db.Departments.Find(id);
            if (department == null)
            {
                return HttpNotFound();
            }
            return View(department);
        }

        // GET: /Department/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Department/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "did,name")] Department department)
        {
            if (ModelState.IsValid)
            {
                db.Departments.Add(department);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(department);
        }

        // GET: /Department/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Department department = db.Departments.Find(id);
            if (department == null)
            {
                return HttpNotFound();
            }
            return View(department);
        }

        // POST: /Department/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "did,name")] Department department)
        {
            if (ModelState.IsValid)
            {
                db.Entry(department).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(department);
        }

        // GET: /Department/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Department department = db.Departments.Find(id);
            if (department == null)
            {
                return HttpNotFound();
            }
            return View(department);
        }

        // POST: /Department/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Department department = db.Departments.Find(id);
            db.Departments.Remove(department);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
